package com.lb.pdm;

import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Fix Schema import statements for all entity classes
 */
public class FixSchemaImports {
    
    private static final String ENTITY_PATH = "src/main/java/com/lb/pdm/entity";
    
    public static void main(String[] args) {
        try {
            Path entityDir = Paths.get(ENTITY_PATH);
            if (!Files.exists(entityDir)) {
                System.err.println("Entity directory not exists: " + entityDir.toAbsolutePath());
                return;
            }
            
            List<Path> javaFiles = Files.walk(entityDir)
                    .filter(path -> path.toString().endsWith(".java"))
                    .collect(Collectors.toList());
            
            System.out.println("Found " + javaFiles.size() + " Java files");
            
            for (Path javaFile : javaFiles) {
                fixSchemaImport(javaFile);
                System.out.println("Fixed Schema import: " + javaFile.getFileName());
            }
            
            System.out.println("\n=== Schema import fix completed! ===");
            
        } catch (Exception e) {
            System.err.println("Error during fix process: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static void fixSchemaImport(Path javaFile) throws IOException {
        String content = Files.readString(javaFile);
        String originalContent = content;
        
        // Check if file contains @Schema but missing import
        if (content.contains("@Schema") && !content.contains("import io.swagger.v3.oas.annotations.media.Schema;")) {
            String[] lines = content.split("\\n");
            StringBuilder newContent = new StringBuilder();
            boolean importAdded = false;
            
            for (String line : lines) {
                newContent.append(line).append("\n");
                
                // Add Schema import after lombok.Data import
                if (line.contains("import lombok.Data;") && !importAdded) {
                    newContent.append("import io.swagger.v3.oas.annotations.media.Schema;\n");
                    importAdded = true;
                }
            }
            
            if (importAdded) {
                content = newContent.toString();
            }
        }
        
        // Only write to file when content changed
        if (!content.equals(originalContent)) {
            Files.writeString(javaFile, content);
        }
    }
}